<?php

declare (strict_types=1);

namespace app\common\service\cms;

use app\common\service\BaseService;
use app\common\exception\AdminException;
use app\common\repository\cms\ArticleRepository;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;

class ArticleService extends BaseService
{
    public function __construct(ArticleRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * 获取文章列表
     *
     * @param array $params
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getList(array $params = []): array
    {
        [$page, $pageSize] = $this->getPaginationParams();
        $where = [];
        if(!empty($params['title'])){
            $where[] = ['title', 'like', '%'.$params['title'].'%'];
        }
        return $this->repository->paginate($where, ['id' => 'desc'], $page, $pageSize);
    }

    /**
     * 获取文章详情信息
     *
     * @param $id
     * @return \app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id): ?\app\common\model\BaseModel
    {
        return $this->repository->getOne($id);
    }

    /**
     * 创建文章信息
     *
     * @param array $data
     * @return \app\common\model\BaseModel|array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create(array $data): \app\common\model\BaseModel|array
    {
        return $this->repository->save($data);
    }

    /**
     * 更新文章信息
     *
     * @param array $data
     * @param $id
     * @return bool|int
     */
    public function update(array $params, $id): bool|int
    {
        if (empty($id)) {
            throw new AdminException('ID 不能为空');
        }
        $data = [
            'cate_id' => $params['cate_id'],
            'title' => $params['title'],
            'image' => $params['image'],
            'desc' => $params['desc'],
            'content' => $params['content'],
            'sort' => $params['sort'],
            'status' => $params['status'],
            'author_name' => $params['author_name'],
        ];
        return $this->repository->update($data, $id);
    }

    /**
     * 删除文章信息
     *
     * @param $id
     * @return bool
     */
    public function delete($id): bool
    {
        return $this->repository->delete($id);
    }
}